package org.opensuse.bs.ui.actions;

import java.util.Vector;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ITreeSelection;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.opensuse.bs.ui.OSC;
import org.opensuse.bs.ui.model.BSModelElement;

public class LinkAction implements IObjectActionDelegate {
	private String srcprj;
	private String srcpkg;
	
	private class LinkDialog extends Dialog {
		private Text desprj;
		private Text despkg;
		
		public LinkDialog(Shell parentShell) {
			super(parentShell);
		}
		
		protected Control createDialogArea(Composite parent) {
			Composite client = new Composite(parent, SWT.NONE);
			GridLayout layout = new GridLayout();
			client.setLayout(layout);
			layout.numColumns = 2;
			
			Label label1 = new Label(client, SWT.NONE);
			label1.setText("Target Project:");
			desprj = new Text(client, SWT.BORDER);
			GridData gd = new GridData();
			desprj.setLayoutData(gd);
			gd.grabExcessHorizontalSpace = true;
			gd.widthHint = 200;
			Label label2 = new Label(client, SWT.NONE);
			label2.setText("Target Package Name:");
			despkg = new Text(client, SWT.BORDER);
			gd = new GridData();
			despkg.setLayoutData(gd);
			gd.grabExcessHorizontalSpace = true;
			gd.widthHint = 200;
			
			return client;
		}
		
		protected void okPressed() {
			final String dprj = desprj.getText().trim();
			final String dpkg = despkg.getText().trim();
			String jobname = "Linking "+dpkg+" from project "+srcprj+" to project "+dprj;
			Job job = new Job(jobname) {
				public IStatus run(IProgressMonitor monitor) {
					String cmd = "linkpac "+srcprj+" "+srcpkg+" "+dprj+" "+dpkg;
					Vector<String> result = OSC.run(cmd);
					if(result.isEmpty()) {
						return Status.CANCEL_STATUS;
					}
					return Status.OK_STATUS;
				}
			};
			job.schedule();
			close();
		}
	}
	
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
	}
	
	public void run(IAction action) {
		Dialog dialog = new LinkDialog(null);
		dialog.open();
	}
	
	public void selectionChanged(IAction action, ISelection selection) {
		if(selection instanceof ITreeSelection) {
			TreePath[] paths = ((ITreeSelection) selection).getPaths();
			srcprj = ((BSModelElement) paths[0].getFirstSegment()).getName();
			srcpkg = ((BSModelElement) paths[0].getLastSegment()).getName();
		}
	}
}
